import React, { Component } from 'react'
import { View, Image, Text, Canvas } from '@tarojs/components'
import { getLocation, downloadFile } from '@tarojs/taro'
import {
  GET_TIAN_QI,
  GET_TIAN_QI_NOW,
  GET_DAY_CALENDAR,
  GET_DAY_CALENDAR_EX,
  GET_DAY_CALENDAR_HOUR,
  GET_DAY_ONE_WORD,
  GET_SUGGEST,
  formatTime
} from '../../api'
import { getLunarDate } from '../../api/calendar'
import "taro-ui/dist/style/components/button.scss" // 按需引入
import './index.scss'
import filePath from "../../assets/bgc.jpg"
// import filePath from "../../assets/bgc.jpg"
import codeImg from "../../assets/codeImg.jpg"


// const barChart = React.createRef();
export default class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      d:{},
      _width: 0, //手机屏宽
      _heigth: 0,//手机屏高
      swiperHeight: 0,//主图图片高度
      canvasType: false,//canvas是否显示
      loadImagePath: '',//下载的图片
      imageUrl: 'http://imgo2o.shikee.com/goods/2019/10/17/201910171144361688.jpg', //主图网络路径
      codeUrl: 'http://imgo2o.shikee.com/couponqrcode/2019/10/18/86_215.jpg',//二维码网络路径
      localImageUrl: '', //绘制的商品图片本地路径
      localCodeUrl: '', //绘制的二维码图片本地路径
      loadType: false  //保存图片，分享好友 Btn
    }
    // const _that=this
  }
  /* 图片加载时 页面加载主图时触发
   <image src="{{item}}" class="img" mode="widthFix" bindload="onSwiperLoad"></image>
  */
  onImgLoad(e) {
    console.log(e);
    let oImgW = e.detail.width; //图片原始宽度
    let oImgH = e.detail.height; //图片原始高度
    let imgWidth = 750; //图片设置的宽度
    let scale = imgWidth / oImgW; //比例计算
    let imgHeight = oImgH * scale;
    console.log(scale, imgHeight);
    this.setState({
      swiperHeight: imgHeight,
    })
  }
  getSysInfo() {
    /*获取手机宽高*/
    let that = this
    let imgUrl = "https://media.gzwrkj.cn/image/sunny_day.jpg"
    // filePath
    let qrcodeUrl = codeImg
    wx.getSystemInfo({
      success(res) {
        console.log(res, 'skdjfsjddjdjdjd');
        that.setState({
          _width: res.windowWidth,
          _heigth: res.windowHeight,
          canvasType: true,
        })
        // 获取图片信息生成canvas
        that.getImginfo([imgUrl, qrcodeUrl], 0);
      }
    })
  }
  // 获取图片信息
  getImginfo(urlArr, _type) {
    let that = this;
    wx.getImageInfo({
      src: urlArr[_type], //服务器返回的带参数的小程序码地址
      success: function (res) {
        console.log(res, '---------res2');
        //res.path是网络图片的本地地址
        if (_type === 0) { //商品图片
          that.setState({
            localImageUrl: res.path,
          })
          that.getImginfo(urlArr, 1)
        } else {
          that.setState({ //二维码
            localCodeUrl: res.path,
            loadType: true,
          })
          // 创建canvas图片
          that.createNewImg();
        }
      },
      fail: function (res) {
        //失败回调
        console.log('错误-res', _type, res)
      }
    });
  }
  getToday() {
    GET_DAY_CALENDAR().then(res => {
      console.log(res);
      if (res.code == '000000') {
        let d = res.data
        d.today = formatTime(new Date())
        d.days=new Date().getDate()
        this.setState({
          d
        })
        this.getSysInfo()
      }
    })
  }
  //绘制canvas
  createNewImg() {
    let _width = this.state._width,
      _heigth = this.state._heigth; //屏幕宽与高

    let imgHeigth = this.state.swiperHeight, //原图片高度
      scale = (_width - 40) / _width, //缩小比例
      that = this;
    let imgH = imgHeigth * scale; //绘制时图片显示高度  
    let ctx = wx.createCanvasContext('mycanvas');
    // 绘制背景
   
    //绘制图片
    ctx.drawImage(this.state.localImageUrl, 0, 0, _width , _heigth);
    // ctx.drawImage(codeImg, _width*0.7, _heigth*0.8, 80 , 80);

    // 绘制标题
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(18);
    // ctx.setFillStyle('#333');

    let txtWidth = _width - 60 + 30 - 100 - 50; //文字的宽度

   
    console.log(this.state.d);
    let d=this.state.d,
    th=_heigth*0.35
    ctx.setFontSize(60);
    // ctx.font = '600 60px';
    // ctx.fillText(d.days, 30, th, txtWidth);
    ctx.fillText(d.days, 30-1, th, txtWidth);
    ctx.fillText(d.days, 30, th-1, txtWidth);
    ctx.setFontSize(16);
    ctx.fillText(d.weekday, 30+80, th, txtWidth);
    let t=d.lunar
    if(d.holiday) t+=`  ${d.holiday}`
    ctx.setFontSize(14);
    ctx.fillText(t, 30, th+30, txtWidth);

    ctx.fillText(`${d.lunarYear}属${d.animalsYear}`, 30, th+60, txtWidth);

    // ctx.setLineWidth(20)
    // ctx.setFillStyle('red')
    // ctx.setStrokeStyle('#fff')
    // ctx.strokeRect(10, _heigth*0.3, 120, 180)
    // ctx.moveTo(_width  - 110, _heigth-110)
    // ctx.lineTo(_width  , _heigth-110)
    ctx.stroke()
    
 //商品名称 最多两行显示 写法有点LOW，但思路是这样的
 let title = 'jhaskhasfkjhh合适的话房间升级'; //商品名称
 let title2; //商品名称
 if (title.length > 10) {
     title2 = title.slice(10, title.length);
     title = title.slice(0, 10);
 }
 if (title2.length > 10) {
     title2 = title2.slice(0, 9) + ' ...';
 }
 ctx.setFontSize(14);
//  ctx.setFillStyle('#fff')
 ctx.font ="华为楷体"
 ctx.fillText(title, 10, _heigth-90, txtWidth);
 ctx.fillText(title2, 10, _heigth-60, txtWidth);
    // 绘制二维码
    ctx.drawImage(codeImg, _width  - 110, _heigth-110, 90, 90);
    // 显示绘制
    ctx.draw();

    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setState({
            loadImagePath: tempFilePath,
          });
          // setTimeout(() => {
            
          //   wx.saveImageToPhotosAlbum({
          //     filePath: tempFilePath,
          //     success(res) {
          //       console.log('res', res);
          //       wx.showToast({
          //         title: '已保存到相册',
          //         icon: 'success',
          //         duration: 3000
          //       })
          //     }
          //   })
          // }, 500);
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 500);
  }
  //点击保存到相册
  saveImg() {
    console.log(this.state.loadImagePath,'---');
    wx.saveImageToPhotosAlbum({
      filePath: this.state.loadImagePath,
      success(res) {
        console.log('res', res);
        wx.showToast({
          title: '已保存到相册',
          icon: 'success',
          duration: 3000
        })
      },
      fail(err) {
        console.log('err', err);
        
      }
    })
  }



  componentDidMount() {
    // var context = wx.createCanvasContext('share')
    // console.log(context,'--');
    // context.setStrokeStyle("#00ff00")
    // context.setLineWidth(1)
    // context.stroke()
    // context.draw()
    // var context = wx.createCanvasContext('share')
    // context.stroke()
    // context.draw()
    this.getToday()
  }




  render() {

    return (
      <View className='bgcPage' onClick={() => this.saveImg()}>

        <View className='everyDayBgc' >
          <Image onLoad={e => this.onImgLoad(e)} className="bgcImg" src={filePath} mode="aspectFill"></Image>
          <Image className="code" src={codeImg} mode="aspectFill"></Image>
        </View>
        {/* hidden={canvasHidden} */}
        <Canvas canvas-id='mycanvas' className='canvas' hidden={true}></Canvas >
        {/* <Image src={shareTempFilePath}  className="showImg" ></Image> */}
      </View>
    )
  }
}
